package com.agnes.phone.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;

import com.agnes.phone.other.MyPhoneStateListener2;

/**
 * 来电时机不可控，如果需要实时监控，则需要一个Service服务在后台长期运行
 */
public class PhoneService extends Service {
    private TelephonyManager tm;
    private MyPhoneStateListener2 listener;

    @Override
    public void onCreate() {
        super.onCreate();
        tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        listener = new MyPhoneStateListener2(this);
        tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        if (listener != null){
            tm.listen(listener,PhoneStateListener.LISTEN_NONE);
            listener = null;
        }
        super.onDestroy();
    }
}
